/*
 * Copyright 2013 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package com.royal.lr.netty;


import com.royal.lr.util.StringUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpUtil;
import io.netty.util.AsciiString;
import io.netty.util.CharsetUtil;
import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Map;

import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

public class NettyHttpServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
    private static final Logger logger = LogManager.getLogger(NettyHttpServerHandler.class);

    private static final byte[] CONTENT = { 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd' };

    private static final AsciiString CONTENT_TYPE = AsciiString.cached("Content-Type");
    private static final AsciiString CONTENT_LENGTH = AsciiString.cached("Content-Length");
    private static final AsciiString CONNECTION = AsciiString.cached("Connection");
    private static final AsciiString KEEP_ALIVE = AsciiString.cached("keep-alive");
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
       /* if (msg instanceof HttpRequest) {
            HttpRequest req = (HttpRequest) msg;


          *//*  FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT));
            response.headers().set(CONTENT_TYPE, "text/plain");
            response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes());*//*

            Map<String, Object> reqData=null;
            String resData="";
            if (req.method() == HttpMethod.GET) {
                logger.info("uri:"+req.uri());
                reqData=getMethodParamsFromChannel(req);
                resData = "GET method over";

            } else if (req.method() == HttpMethod.POST) {
                reqData=postMethodParamsFromChannel(req);
                resData = "POST method over";
            }
            logger.info("reqData:"+reqData);
            ByteBuf buf =  Unpooled.wrappedBuffer(resData.getBytes(CharsetUtil.UTF_8));
           // response = responseOK(HttpResponseStatus.OK, resData);

        }*/
        logger.info("test");
        Map<String, Object> reqData=null;
        String resData="success";
        try {
           reqData=new RequestParser(msg).parse();
        } catch (UnsupportedEncodingException e) {
            logger.error("转换异常：",e);
        }
        logger.info("reqData:"+reqData);
        String testParam=(String) reqData.get("testParam");
        if(StringUtil.isNotEmpty(testParam)){

        }else{
        }
        String path=System.getProperty("user.dir")+"/logs/daily/daily.log";
        logger.info("path:"+path);
        String logData="";
        while (!logData.contains("返回值")){
            logData=FileUtils.readFileToString(new File(path),"utf-8");
        }
        for(String data:logData.split("\n")){
            if(data.contains("返回值")){
                resData=data.substring(data.indexOf("返回值")+4);
            }
        }
        String test=new String(resData.getBytes(CharsetUtil.UTF_8));
        logger.info("resData:"+test);
        boolean keepAlive = HttpUtil.isKeepAlive(msg);
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK,  Unpooled.wrappedBuffer(resData.getBytes(CharsetUtil.UTF_8)));
        response.headers().set(CONTENT_TYPE, "text/plain;charset=utf-8");
        response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes());
        if (!keepAlive) {
            ctx.write(response).addListener(ChannelFutureListener.CLOSE);
        } else {
            response.headers().set(CONNECTION, KEEP_ALIVE);
            ctx.write(response);
        }

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }

}
